﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using MShop.Core.DataAccess;
using MShop.Core.Domain;

namespace MShop.Core.Service.Membership
{
    public class DefaultRoleService:IRoleService
    {

        private readonly ICommonDao<aspnet_Roles> _CommonDao;

        public DefaultRoleService( ICommonDao<aspnet_Roles> commonDao)
        {
            _CommonDao = commonDao;
        }

        #region IRoleService Members

        public void UpdateUserRole(string userName, string roleName)
        {
            MembershipUser user = System.Web.Security.Membership.GetUser(userName);
       
            if (Roles.GetRolesForUser(user.UserName).Length > 0)
            {
                Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
            }
            Roles.AddUserToRole(user.UserName, roleName);            
        } 


        public IQueryable<aspnet_Roles> FindPowerRoles()
        {
              return  _CommonDao.Find(x => x.Description != null);
        }

       


        public Guid[] PowersRoleId
        {
            get 
            {
                return FindPowerRoles().Select(x => x.RoleId).ToArray();
            }
        }

        #endregion

        #region IRoleService Members


        public IQueryable<aspnet_Roles> FindRoles()
        {
            return _CommonDao.Find(x => x.Description == null);
        }

        #endregion

        #region IRoleService Members


        public bool IsPowerRole(string userName)
        {
            string[] roles = System.Web.Security.Roles.GetRolesForUser(userName);
            foreach (string role in roles)
            {
                var r=  FindPowerRoles().FirstOrDefault(x => x.LoweredRoleName == role.ToLower());
                if (r != null)
                    return true;
            }

            return false;
        }

        #endregion
    }
}